package com.bwton.msx.ccb.ui.auth;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.bwton.msx.ccb.R;
import com.bwton.msx.ccb.databinding.FragmentLoginBinding;
import com.bwton.msx.ccb.service.api.ApiServiceManager;
import com.bwton.msx.ccb.service.api.response.LoginResult;
import com.bwton.msx.ccb.service.auth.AuthService;
import com.bwton.msx.ccb.service.user.User;
import com.bwton.msx.ccb.service.user.UserManager;
import com.bwton.msx.ccb.utils.RxViewUtils;

import java.util.Objects;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class LoginFragment extends Fragment {
    private CompositeDisposable disposable = new CompositeDisposable();
    private FragmentLoginBinding binding;
    private AuthService authService = new AuthService(ApiServiceManager.getAuth());
    private final String TAG = "登录";
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        binding = FragmentLoginBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        disposable = new CompositeDisposable();
        Disposable smsEvent = RxViewUtils.throttle(binding.btnSms, 10).subscribe(v -> {
            String phone = binding.inputPhone.getEditableText().toString();
            if (phone.length() != 11) {
                Toast.makeText(requireContext(), "手机号不正确!", Toast.LENGTH_SHORT).show();
                return;
            }
            Disposable sms = authService.sendLoginSms(Objects.requireNonNull(binding.inputPhone.getText()).toString().trim())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(result -> {
                        binding.textRequest.setText("response:\n"+result.toString());
                        Toast.makeText(requireContext(), result.errmsg, Toast.LENGTH_SHORT).show();
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            throwable.printStackTrace();
                        }
                    });
            disposable.add(sms);
        });
        disposable.add(smsEvent);

        Disposable registerEvent = RxViewUtils.throttle(binding.btnSubmit,5).subscribe(v->{
            String phone = binding.inputPhone.getEditableText().toString();
            if (phone.length() != 11) {
                Toast.makeText(requireContext(), "手机号不正确!", Toast.LENGTH_SHORT).show();
                return;
            };
            String sms = binding.inputSms.getEditableText().toString();
            if (sms.length() != 4) {
                Toast.makeText(requireContext(), "验证码不正确!", Toast.LENGTH_SHORT).show();
                return;
            };
            Disposable register = authService.loginBySms(phone,sms)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(result->{
                        binding.textRequest.setText("response:\n"+result.toString());
                        if (result.success){
                            onUserLogin(result.getResult());
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            throwable.printStackTrace();
                        }
                    });
            disposable.add(register);
        });
        disposable.add(registerEvent);
    }
    private void onUserLogin(LoginResult result){
        User user = new User();
        user.unionId = result.getUser().getUnion_id();
        user.userId = result.getUser().getUser_id();
        user.token = result.getUser_token();
        user.phone = result.getUser().getMobile_phone();
        user.state.setEnableRealName(result.getUser().getAuth_status() == 1);
        UserManager.getInstance().login(user);
        NavHostFragment.findNavController(this).navigateUp();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
        disposable.dispose();
        disposable.clear();
    }

}